<template>
  <div class="chart-container ps_w_h_100" ref="chartContainer" role="img">
    <div ref="chartDOM" class="ps_w_h_100" tabindex="0"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import china from '@/utils/china.json'

echarts.registerMap('china', china)

const countValue = ref(0)
let timer = null
let currentIndex = -1
let NodeIndex = 0
const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  autoSet: {
    type: Boolean,
    default: true
  },
  tooltipAnimation: {
    type: Boolean,
    default: false
  },
  tAnimationConfig: {
    type: Object,
    default: () => ({
      Basis: 'x',
      Duration: 2000,
      Length: 99
    })
  }
})

const chartDOM = ref()
let myChart = null
const observerDom = ref()
const chartContainer = ref()

const chartInitOption = ref({
  renderer: 'svg'
})

const defaultOption = ref({
  backgroundColor: '',
  darkMode: 'auto'
})

// 切换tooltip
function switchTooltip(chartInstance) {
  if (!chartInstance) return

  // 取消之前高亮的图形
  if (currentIndex >= 0) {
    chartInstance.dispatchAction({
      type: 'downplay',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
  }

  const length = props.tAnimationConfig?.Length || 10

  if (props.tAnimationConfig?.Basis === 'y') {
    // 降序
    if (currentIndex <= 0) {
      currentIndex = length - 1
    } else {
      currentIndex = currentIndex - 1
    }
  } else {
    // 默认升序 (Basis 为 'x' 或其他值)
    currentIndex = (currentIndex + 1) % length
  }

  const RatedValue = 6
  let startValue = 0
  let endValue = RatedValue
  const MultipleValue = Math.floor(currentIndex / RatedValue)

  startValue = MultipleValue * RatedValue
  endValue = (MultipleValue + 1) * RatedValue

  const options = chartInstance.getOption()
  const Hastreemap = options.series.findIndex(item => item.type === 'treemap')
  const Nodes = []

  if (Hastreemap >= 0) {
    if (Nodes.length === 0) options.series[Hastreemap].data.forEach(item => Nodes.unshift(item.name))

    chartInstance.dispatchAction({
      type: 'treemapRootToNode',
      targetNodeId: Nodes[NodeIndex]
    })
    NodeIndex = NodeIndex + 1
    if (NodeIndex >= Nodes.length) {
      chartInstance.dispatchAction({
        type: 'treemapRootToNode',
        targetNodeId: '总览'
      })
      NodeIndex = 0
    }
  } else {
    // 显示tooltip
    chartInstance.dispatchAction({
      type: 'dataZoom',
      startValue,
      endValue: endValue
    })

    // 显示tooltip
    chartInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
  }
}

function startTooltipLoop(chartInstance) {
  closeSwitchTooltip()

  if (!props.tooltipAnimation) return

  const duration = props.tAnimationConfig?.Duration || 2000
  timer = setInterval(() => switchTooltip(chartInstance), duration)
}

function closeSwitchTooltip() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

function cleanupChart() {
  closeSwitchTooltip()

  if (myChart) {
    try {
      myChart.dispose()
    } catch (e) {
      console.warn('Error disposing chart:', e)
    }
    myChart = null
  }

  window.removeEventListener('resize', handleResize)
  observerDom.value?.disconnect()
}

function handleResize() {
  if (myChart && typeof myChart.resize === 'function') {
    myChart.resize()
  }
}

const loadChart = async () => {
  if (!chartDOM.value) {
    console.warn('Chart container not found')
    return
  }

  try {
    await nextTick()

    // 清理现有图表
    cleanupChart()

    // 初始化新图表
    myChart = echarts.init(chartDOM.value, null, chartInitOption.value)
    if (!myChart) {
      console.error('Failed to initialize chart')
      return
    }

    const option = Object.assign({}, defaultOption.value, props.option)
    myChart.setOption(option, true)
    // 设置resize监听
    window.addEventListener('resize', handleResize)

    observerDom.value = new ResizeObserver(() => {
      if (myChart) {
        myChart.resize()
      }
    })

    if (chartContainer.value) {
      observerDom.value.observe(chartContainer.value, { box: 'border-box' })
    }

    // 设置动画
    if (props.tooltipAnimation) {
      startTooltipLoop(myChart)
      myChart.setOption({
        tooltip: {
          borderColor: '#4195d2',
          valueFormatter: value => {
            return Number(value).toFixed(2)
          },
          backgroundColor: 'rgba(11, 43, 89,0.7)',
          textStyle: {
            color: '#9cdcfe'
          }
        }
      })
    }

    // 设置事件监听器
    myChart.off('mouseover')
    myChart.off('mouseout')

    myChart.on('mouseover', () => {
      closeSwitchTooltip()
    })

    myChart.on('mouseout', () => {
      if (props.tooltipAnimation) {
        startTooltipLoop(myChart)
      }
    })

   
  } catch (error) {
    console.error('Error initializing chart:', error)
  }
}

const updateChartOption = option => {
  if (myChart && typeof myChart.setOption === 'function') {
    myChart.setOption(option, true)
  }
}

watch(
  () => props.option,
  newVal => {
    if (props.autoSet || countValue.value === 0) {
      loadChart()
      countValue.value += 1
    } else if (myChart) {
      const option = Object.assign({}, defaultOption.value, newVal)
      myChart.setOption(option, true)
    }
  },
  { deep: true, immediate: true }
)

defineExpose({
  updateChartOption,
  resize: () => {
    if (myChart) {
      myChart.resize()
    }
  }
})

onMounted(() => {
  loadChart()
})

onUnmounted(() => {
  closeSwitchTooltip()
  cleanupChart()
})
</script>

<style scoped lang="scss">
.chart-container {
  position: relative;
}
</style>
